<?php

namespace App\Http\Controllers\Alipay;

use App\Models\Category;
use App\Models\CategoryUser;
use App\Models\Goods;
use App\Models\GoodsClass;
use App\Models\GoodsCustom;
use App\Models\GoodsSetmeal;
use App\Models\GoodsSpec;
use App\Services\CommonService;
use App\Services\GoodsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class GoodsController extends BaseVerifyController
{
    /**
     * 商品详情
     */
    public function getGoodsInfo(Request $request){
        $goods_id = $request->input('goods_id');
        if($goods_id){

                $goods = Goods::getGoodsInfo($goods_id);
                if(!empty($goods)){
                    $goods['month_rent'] = ceil($goods['min_price'] * 30);
                    $goods['max_foregift'] = GoodsSetmeal::getMaxForegift($goods_id);

                    $buyout_price= GoodsSetmeal::where(['goods_id'=>$goods_id,'is_delete'=>CommonService::GOODS_IS_DELETE_NOT])->value('buyout_price');
                    if($goods['min_price']&&$goods['min_lease_term']&&$buyout_price){
                        $goods['min_price'] = bcsub($goods['min_price'],$buyout_price/$goods['min_lease_term'],2);
                    }
                    Redis::hset(GoodsService::GOODS_INFO_KEY,$goods_id,json_encode($goods));
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品已下架');
                }
            // }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$goods);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少商品ID');
        }
    }


    /**
     * 获取商品套餐信息
     */
    public function getGoodsSetmeal(Request $request){
        $goods_id = $request->input('goods_id');
        if($goods_id){
            $setmeal = Goods::apiRentGoodsMealSpecInfo($goods_id);
//            foreach ($setmeal as $k=>$v){
//                $setmeal[$k]['title'] = $v['title'].'('.GoodsService::GOODS_RENT_TYPE_NAME_LIST[$v['lease_set']].GoodsService::GOODS_BUYOUT_NAME_LIST[$v['is_buy_out']].')';
//                $setmeal[$k]['spec'] = GoodsSpec::GetGoodsSpecData($v['goods_id'],$v['id'],$v['lease_set'],$v['is_huabei']);
//                $setmeal[$k]['fixed_day_price'] =bcsub($setmeal[$k]['spec'][0]['total_amount']/$setmeal[$k]['spec'][0]['lease_time'],$v['buyout_price']/$setmeal[$k]['spec'][0]['lease_time'],2);
//                $setmeal[$k]['fixed_first_rent'] =bcdiv($setmeal[$k]['fixed_day_price']*$setmeal[$k]['spec'][0]['lease_time'],12,2);
//            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$setmeal);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少商品ID');
        }
    }


    /**
     * 获取商品套餐租赁方式
     */
    public function getGoodsRentSetmeal(Request $request){
        $goods_id = $request->input('goods_id');
        if($goods_id){
            $setmeal=[
                ['id'=>1,'title'=>"租完归还/续租/买断"],
                ['id'=>2,'title'=>"租完12期即送-租满6个月后支持随租随还"]
            ];
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$setmeal);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少商品ID');
        }
    }


    /**
     * 获取商品参数信息
     */
    public function getGoodsParameter(Request $request){
        $goods_id = $request->input('goods_id');
        if($goods_id){
            $data = GoodsCustom::getGoodsAttribute($goods_id);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少商品ID');
        }
    }

    /**
     * 获取分类
     */
    public function getCategory(){
        $data = Redis::get(Category::REDIS_CATEGORY);
        if(empty($data)){
            $category = Category::where([['enabled',Category::CATEGORY_STATUS_DISPLAY],['is_delete',Category::CATEGORY_NOT_DELETE]])
                ->select('id','name','image','parentid')->orderBy('displayorder','asc')->get();
            $category = $category ? $category->toArray() : [];
            $data = [];
            if(!empty($category)){
                $generateTree = function ($items, $parentKey = 'parentid') {
                    $tree = $temp = [];
                    foreach ($items as $item) {
                        $temp[$item['id']] = $item;
                    }
                    foreach ($items as $item) {
                        if (isset($temp[$item[$parentKey]])) {
                            $temp[$item[$parentKey]]['sub'][] = &$temp[$item['id']];
                        } else {
                            $tree[] = &$temp[$item['id']];
                        }
                        // 下面可以去掉 pid 元素
                        unset($temp[$item['id']][$parentKey]);
                    }
                    return $tree;
                };
                $data = $generateTree($category);
                Redis::set(Category::REDIS_CATEGORY,json_encode($data));
            }
        }else{
            $data = json_decode($data,true);
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

    public function getGoodsListByCategory(Request $request){

        $category=Redis::get(GoodsClass::goods_class_category);
        $category=json_decode($category,true);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$category);
    }
    /**
     * 获取商品列表
     */
    public function getGoodsList(Request $request){
        $goods_name = trim($request->input('goods_name'));
        $orderby_name = $request->input('orderby_name','goods_sort');
        $sort = $request->input('sort','asc');
        $min_price = $request->input('min_price','');
        $max_price = $request->input('max_price','');
        $category_id = $request->input('category_id','');
        $cateId = $request->input('cate_id','');

        $page = $request->input('page');
        $pageSize = $request->input('pageSize')??100;
        $where[] = ['status',GoodsService::GOODS_STATUS_PUT];
        $where[] = ['is_show',GoodsService::GOODS_IS_SHOW_YES];
        $where[] = ['is_delete',CommonService::GOODS_IS_DELETE_NOT];
        $where[] = ['member_id','=','1731928096'];

        if(!empty($goods_name)){
            $where[] = ['title','like','%'.trim($goods_name).'%'];
        }
        if(!empty($category_id)){
            $where[] = ['category_id',$category_id];
        }

        if(!empty($cateId)){
            $where[] = ['subclass_id',$cateId];
        }
        if(!empty($min_price)){
            $where[] = ['min_price','>',$min_price];
        }
        if(!empty($max_price)){
            $where[] = ['min_price','<',$max_price];
        }
        $goods = Goods::where($where)->select('id','title','rent_label','imgurl','category_id','subclass_id','min_price','min_line_price','min_lease_term','new_grade',
            'discount_type','discount_name','business_type')
            ->orderby($orderby_name,$sort)
            ->orderby('id','desc')
            ->paginate($pageSize);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $goods);
    }


    /**
     * 获取商品列表
     */
    public function getHomeGoodsList(Request $request){
        $min_price = $request->input('min_price','');
        $max_price = $request->input('max_price','');
        $page = $request->input('page');
        $pageSize = $request->input('pageSize')??10;
        $where[] = ['status',GoodsService::GOODS_STATUS_PUT];
        $where[] = ['is_show',GoodsService::GOODS_IS_SHOW_YES];
        $where[] = ['is_delete',CommonService::GOODS_IS_DELETE_NOT];

        if(!empty($goods_name)){
            $where[] = ['title','like','%'.trim($goods_name).'%'];
        }

        if(!empty($min_price)){
            $where[] = ['min_price','>',$min_price];
        }
        if(!empty($max_price)){
            $where[] = ['min_price','<',$max_price];
        }
        $goods = Goods::where($where)->select('id as goods_id','title','imgurl as image','min_price','min_lease_term','discount_name','rent_label','min_line_price','business_type','new_grade')
            ->orderby('goods_sort','desc')->paginate($pageSize);
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods['data'])){
            foreach ($goods['data'] as $k=>&$v){
                $v['goodsInfo']=[
                    'business_type'=>$v['business_type'],
                    'business_type_name'=>$v['business_type_name'],
                    'discount_name'=>$v['discount_name'],
                    'min_lease_term'=>$v['min_lease_term'],
                    'min_line_price'=>$v['min_line_price'],
                    'min_price'=>$v['min_price'],
                    'new_grade'=>$v['new_grade'],
                    'position_img_full'=>$v['position_img_full'],
                    'rent_label'=>$v['rent_label'],
                ];
            }
        }


        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $goods);
    }


    /**
     * 获取商品列表
     */
    public function getGoodsCateList(Request $request){
        $parentid = $request->input('parentid');
        $category_ids = Category::where([['enabled',Category::CATEGORY_STATUS_DISPLAY],['is_delete',Category::CATEGORY_NOT_DELETE]])
            ->where('parentid',$parentid)->pluck('id');

        $page = $request->input('page');
        $pageSize = $request->input('pageSize')??100;
        $where[] = ['status',GoodsService::GOODS_STATUS_PUT];
        $where[] = ['is_show',GoodsService::GOODS_IS_SHOW_YES];
        $where[] = ['is_delete',CommonService::GOODS_IS_DELETE_NOT];
        $where[] = ['member_id','=','1731928096'];

        $goods = Goods::where($where)->select('id','title','rent_label','imgurl','min_price','min_lease_term')
            ->whereIn('category_id',$category_ids)
            ->orderby('category_id','asc')->orderby('goods_sort','asc')->paginate($pageSize);
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods['data'])){
            foreach ($goods['data'] as $k=>$v){
                $buyout_price= GoodsSetmeal::where(['goods_id'=>$v['id'],'is_delete'=>CommonService::GOODS_IS_DELETE_NOT])->value('buyout_price');
                if($v['min_price']&&$v['min_lease_term']&&$buyout_price){
                    $goods['data'][$k]['min_price'] = bcsub($v['min_price'],$buyout_price/$v['min_lease_term'],2);
                }
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $goods);
    }

    /**
     * 获取商品碎屏险
     */
    public function getInsuranceList(Request $request){

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', GoodsService::GOODS_INSURANCE_LIST);

    }

    /**
     * 获取联通冲浪卡
     * @param Request $request
     * @return false|string
     */
    public function getCardList(Request $request){
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', GoodsService::GOODS_UNIWAP_LIST);
    }



}
